package com.cipe.cmrs.security;

import java.io.IOException;
import java.util.Map;

import javax.servlet.ServletException;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;

import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.security.core.Authentication;
import org.springframework.security.web.authentication.SavedRequestAwareAuthenticationSuccessHandler;
import org.springframework.stereotype.Component;

import com.cipe.cmrs.model.User;
import com.cipe.cmrs.service.RestrictedUiElementsService;

@Component("postSuccessAuthHandler")
public class PostSuccessfulAuthenticationHandler extends SavedRequestAwareAuthenticationSuccessHandler {
    private static final String ATTR_ALLOWED_ELEMENTS = "allowedUiElements";
    @Autowired
    RestrictedUiElementsService restrictedUiElementsService;

    public void onAuthenticationSuccess(HttpServletRequest request, HttpServletResponse response, Authentication authentication)
        throws ServletException, IOException {
        // Never invalidate session as requested by Andy (5/14/2012)
        request.getSession().setMaxInactiveInterval(-1);
        User user = (User) authentication.getPrincipal();
        Map<String, Map<String, String>> allowedUiElementsMap = restrictedUiElementsService.getAllAllowedUiElements(user);
        user.setAllowedUiElementsMap(allowedUiElementsMap);
        request.getSession().setAttribute(ATTR_ALLOWED_ELEMENTS, allowedUiElementsMap);
        response.sendRedirect("secure/showDashboard.do");
    }
}